<%@ Page Language="C#"%>
<%@ Import Namespace="System.Diagnostics"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="Muki.Framework.Util"%>
<%@ Import Namespace="Muki.Framework.Wxf"%>
<%@ Import Namespace="Dot.StreamObject"%>

<script runat="server" language="C#">

    private string _APP_PATH     = "";
    private string ZZSetting_File = "";
		private string ZZTemporary_Directory     = "../temp";
    private int    _Wizard       = 0;
    private string cASP_NET_SUPPORT="<div style=\"font-weight: normal;color: red\">No</div>";
    private string ZZTemporary_Writeable="<div style=\"font-weight: normal;color: red\">No</div>";
    private string ZZSetting_Writeable="<div style=\"font-weight: normal;color: red\">No</div>";
    private string ZZDatabase_Blank_Avaliable="<div style=\"font-weight: normal;color: red\">No</div>";
    
    private string cDatabase_Blank         ="install\\sql\\fms_muki.sql";

    private string lnk_database_host       ="127.0.0.1";
    private string lnk_database_username   ="sa";
    private string lnk_database_password   ="";
    private string lnk_database_name       ="";
		private string lnk_Wizard_Step         ="";
		private string Wizard_Message          ="";
		
    void Page_Load(Object sender, EventArgs e)
    {
            _APP_PATH = Request.ServerVariables["APPL_PHYSICAL_PATH"];

            string ZHTMLWindow = "";

            StringBuilder XCodeObject = new StringBuilder();

            Version _Version = System.Environment.Version;
            string cVersion=_Version.ToString();
            string cLOGON_LANG="";
            lnk_Wizard_Step =ZZGeneral.XRequest("lnk_Wizard_Step");
            if (lnk_Wizard_Step=="")
            {
                lnk_Wizard_Step="3";
            }
            if (_Version.Major>=4)
            {
                cASP_NET_SUPPORT="<div style=\"font-weight: normal;color: green\">Yes</div>";
            }
            try
            {
                string cHTTP_ACCEPT_LANGUAGE = HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"];
                if (cHTTP_ACCEPT_LANGUAGE==null)
                {
                    cHTTP_ACCEPT_LANGUAGE="";
                }
                cLOGON_LANG=cHTTP_ACCEPT_LANGUAGE.ToLower();

                //XStream oXStream    = new XStream();
                ///XCodeObject = oXStream.XReadStream(_APP_PATH + "Templates\\Install.dat");

            }
            catch (Exception ex)
            {
                //ZZTrace.Write(ZFILE_NAME, "Exception,Message=[" + ex.Message + "]" + "<HR>Source=[" + ex.Source + "]<HR>StackTrace=[" + ex.StackTrace + "]<HR>TargetSite=[" + ex.TargetSite + "]");
                //Response.Write(ex.Message);
            }
            finally
            {
            }

            ZZSetting_File=_APP_PATH+"cfg\\setting.config";
						bool Completed_Setting=false;
            try
            {
                checked
                {

										ZZSetting_Writeable=Setting_Writeable();
										ZZTemporary_Writeable=Log_Writeable();
										
                     lnk_database_host      =ZZGeneral.XRequest("lnk_database_host");
                     lnk_database_username  =ZZGeneral.XRequest("lnk_database_username");
                     lnk_database_password  =ZZGeneral.XRequest("lnk_database_password");
                     lnk_database_name      =ZZGeneral.XRequest("lnk_database_name");
            
                    if (lnk_database_host=="")
                    {
                        lnk_database_host="localhost";
                    }
                    if (lnk_database_username=="")
                    {
                        lnk_database_username="sa";
                    }
                    if (lnk_database_name=="")
                    {
											Wizard_Message="please input database name";
										}
                    string dbAdapter="server="+lnk_database_host+";uid="+lnk_database_username+";pwd="+lnk_database_password+";database=master;";

                    string cdatabases	="";
                    try
                    {
                        Setting.Instance().Clear();

                        Setting.Instance().AddNewDatabase("NIX", DatabaseVendor.MsSqlServer, dbAdapter, _APP_PATH + "cfg\\ClassMap.xml");

                        StreamContext _Trans = new StreamContext();

                        _Trans.dbName      = "NIX";

                        QueryRows Rssysdatabases = new QueryRows(_Trans);
                        Rssysdatabases.CommandText = "select name from sysdatabases where name='"+ lnk_database_name +"'";
                        Rssysdatabases.Open();
                        if (Rssysdatabases.EOF)
                        {
	                        _Wizard++;
	                      }else{
		                        QueryRows Rssysobjects = new QueryRows(_Trans);
		                        Rssysobjects.CommandText = "select name from "+lnk_database_name+"..sysobjects where name='init_temp' and type='U'";
		                        Rssysobjects.Open();
		                        if (Rssysobjects.EOF)
		                        {
																Rssysobjects.Close();

				                        Rssysobjects.CommandText = "select name from "+lnk_database_name+"..sysobjects where type='U'";
				                        Rssysobjects.Open();
				                        if (Rssysobjects.EOF)
				                        {
			                        			_Wizard++;
																}else
																{
																		Wizard_Message="database already exist";
																}
																Rssysobjects.Close();

			                    	}else{
	                        		_Wizard++;
			                    	}
			                    	Rssysobjects.Close();
                        }
                        Rssysdatabases.Close();

						            cDatabase_Blank = _APP_PATH+cDatabase_Blank;

												List<string> _Data=ParseSqlFile(cDatabase_Blank);
                      	
                      	_Trans.DoSqlNonQueryString("CREATE DATABASE "+lnk_database_name);

		                    dbAdapter="server="+lnk_database_host+";uid="+lnk_database_username+";pwd="+lnk_database_password+";database="+lnk_database_name;
                        Setting.Instance().Clear();

                        Setting.Instance().AddNewDatabase("NIX", DatabaseVendor.MsSqlServer, dbAdapter, _APP_PATH + "cfg\\ClassMap.xml");

                        _Trans = new StreamContext();

                        _Trans.dbName      = "NIX";
												foreach (string s in _Data)
												{
													_Trans.DoSqlNonQueryString(s);
												}						
												Completed_Setting=true;
                    }
                    catch (Exception ex)
                    {
												Wizard_Message="Cannot connect to database. User or password is invalid or you have no permittions to create database."+ex.Message;
                    }

										if (Completed_Setting)
										{
				    						string _dbAdapter="server="+lnk_database_host+";uid="+lnk_database_username+";pwd="+lnk_database_password+";database="+lnk_database_name+";";
		
				    						VContexts _VContexts=new VContexts();
				    						_VContexts.Indented=true;
												_VContexts.setBoolean("debug",true);
												_VContexts.setBoolean("cache",false);
		
				    						VContexts _NIX=new VContexts();
		
				    						_NIX.Indented=true;
												_NIX.setValue("Caption","NIX");
												_NIX.setValue("Type","MsSqlServer");
												_NIX.setValue("ConnectionString",_dbAdapter);
		
				    						VContexts _NIX2=new VContexts();
		
				    						_NIX2.Indented=true;
												_NIX2.setValue("Caption","NIX2");
												_NIX2.setValue("Type","MsSqlServer");
												_NIX2.setValue("ConnectionString",_dbAdapter);
		
												_VContexts.setValue("NIX",_NIX);
												_VContexts.setValue("NIX2",_NIX2);
		
		                     StreamWriter _Setting = new StreamWriter(ZZSetting_File, false);
		                    _Setting.WriteLine(_VContexts.Json());
		                    _Setting.Flush();
		                    _Setting.Close();

							        	Response.Redirect("..");
		                    
                  	}
                }
            }
            catch (Exception ex)
            {
               // ZZTrace.Write(ZFILE_NAME, "Exception,Message=[" + ex.Message + "]" + "<HR>Source=[" + ex.Source + "]<HR>StackTrace=[" + ex.StackTrace + "]<HR>TargetSite=[" + ex.TargetSite + "]");
                Response.Write(XCodeObject.ToString());
            }
    }

        public string Setting_Writeable()
        {
						string   _Setting_Writeable="<div style=\"font-weight: normal;color: red\">No</div>";
            if (File.Exists(ZZSetting_File))
            {
                try
                {
                    if (File.Exists(_APP_PATH+"cfg\\setting2.config"))
                    {
                        File.Delete(_APP_PATH+"cfg\\setting2.config");
                    }
                    File.Move(ZZSetting_File,_APP_PATH+"cfg\\setting2.config");
                    File.Move(_APP_PATH+"cfg\\setting2.config",ZZSetting_File);
                    _Setting_Writeable="<div style=\"font-weight: normal;color: green\">Writeable</div>";
                    _Wizard++;
                }
                catch (Exception ex)
                {
                }
            }else{
                try
                {

                    StreamWriter swerr = new StreamWriter(ZZSetting_File, false);
                    swerr.WriteLine("test");
                    swerr.Flush();
                    swerr.Close();

                    if (File.Exists(ZZSetting_File))
                    {
                        File.Delete(ZZSetting_File);
                    }
                    _Setting_Writeable="<div style=\"font-weight: normal;color: green\">Writeable</div>";
                    _Wizard++;
                }
                catch (Exception ex)
                {
                }

            }
		        return _Setting_Writeable;
				}

        public string Log_Writeable()
        {
    				string _Log_Writeable="<div style=\"font-weight: normal;color: green\">No</div>";
            try
            {
                if (!Directory.Exists(_APP_PATH+"temp"))
                {
                    Directory.CreateDirectory(_APP_PATH+"temp");
                }
                ZZTemporary_Directory=_APP_PATH+"temp";

                StreamWriter swerr = new StreamWriter(_APP_PATH+"temp\\read.log", false);
                swerr.WriteLine("testing");
                swerr.Flush();
                swerr.Close();

                if (File.Exists(_APP_PATH+"temp\\read.log"))
                {
                    File.Delete(_APP_PATH+"temp\\read.log");
                }
                _Log_Writeable="<div style=\"font-weight: normal;color: green\">Writeable</div>";
                _Wizard++;
            }
            catch (Exception ex)
            {
            }
            return _Log_Writeable;
				}			

        public string DataBase_Catalogs()
        {
				   return "";
				}

        public List<string> ParseSqlFile(string cFileName)
        {
							List<string> _Data = new List<string>();        	

	            if (File.Exists(cFileName))
	            {
									ZZDatabase_Blank_Avaliable="<div style=\"font-weight: normal;color: green\">Yes</div>";
		              StreamReader _Reader = new StreamReader(cFileName,Encoding.UTF8);
		              
		              long  NDX=0;
		              string SQLString="";
		              string s3="";
		              string LN_STATUS="";
		              string cColumns="";
		              bool   SkipLine=false;
		              bool   _Compress=false;
		              while ((s3 = _Reader.ReadLine()) != null)
		              {
		               		s3=s3.Replace("\\","\\\\");;
		               		s3=s3.Replace("\\n","\n");;
		               		s3=s3.Replace("\\r","\r");;
		              
		                  SkipLine=false;
		                  if (NDX<500)
		                  {
		                      if (s3.Length>2)
		                      {
		                          if (s3.IndexOf(">=")==0  && cColumns=="")
		                          {
		                              cColumns=s3.Replace(">=","");;
		                              SkipLine=true;
		                              _Compress=true;
		                          }else	if (s3.IndexOf("//") == 0)
		                          {
		                              SkipLine=true;
		                          }
		                      }
		                  }
		                  if (!SkipLine)
		                  {
		                      if (_Compress)
		                      {
		                          if (s3==">=" && cColumns!="")
		                          {
		                              s3=cColumns;
		                          }
		                      }
		
		                      if ( ((LN_STATUS=="E" && (s3=="" || s3=="GO")) || (LN_STATUS=="F" && s3=="GO") ) && SQLString!="")
		                      {
		                					//_row++;
															_Data.Add(SQLString);
		                          //SQL++;
		                          SQLString="";
		                          LN_STATUS="";
		                      }else{
		                          SQLString=SQLString+s3;
		                          if (s3!="")
		                          {
		                              LN_STATUS="";
		                              if (s3.Length>=3)
		                              {
		                                  string result = s3.Substring(s3.Length-2, 2);
		                                  if (result==");")
		                                  {
		                                      LN_STATUS="E";
		                                  }else if (s3.Substring(s3.Length-1,1)==";")
		                                  {
		                                      LN_STATUS="F";
		                                  }
		                              }
		                          }
		                      }
		                  }
		                  NDX++;
		              }
		              _Reader.Close();
            	}
            	return _Data;
				}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>MUKI Installation Wizard</title>
    </head>
    <body>
        <form name="MUKI_installation_wizard" method="post">
            <input type="hidden" name="lnk_Wizard_Step" value="{$Wizard_Step$}" />
            <table cellpadding="0" cellspacing="0" border="0" width="80%" align="center" style="margin-top: 2px;">
                <tr>
                    <td align="left" nowrap=1>
                        <h3>Welcome to the MUKI Installation Wizard.</h3>
                    </td>
                </tr>
                <tr>
                    <td align="center" nowrap=1>
                        <table cellpadding="3" cellspacing="3" align="center" border="0">
                            <tr>
                                <td colspan="1" align=left>Select install wizard language:
                                    <td colspan="7" align=left>
                                        <select autocomplete='off' name='inst_lang'>English
                                            <option selected value='C'>English</option>
                                            <option  value='zh_CN'>Chinese Simplifed</option>
                                        </select>
                                    </td>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="8" align=left><h4>1. System Diagnostics</h4></td>
                            </tr>
                            <tr>
                                <td align="left">Test</td>
                                <td align="left">Value</td>
                                <td align="left">Comments</td>
                                <td></td>
                            </tr>
                            <tr>
                                <td width="280" style="color: #666666;" nowrap=1 align=left>Asp.net Version</td>
                                <td width="35" nowrap=1 align=left><%=System.Environment.Version%></td>
                                <td width="35" nowrap=1 align=left><%=cASP_NET_SUPPORT%></td>
                                <td width="70%" nowrap=1></td>
                            </tr>
                            <tr>
                                <td align="left" style="color: #666666;">Configuration file</td>
                                <td  align="left"><%=ZZSetting_File%></td>
                                <td align="left"><%=ZZSetting_Writeable%></td>
                            </tr>
                            <tr>
                                <td align="left" style="color: #666666;">Temporary directory</td>
                                <td align="left"><%=ZZTemporary_Directory%>\*</td>
                                <td align="left"><%=ZZTemporary_Writeable%></td>
                            </tr>
                            <tr>
                                <td align="left" style="color: #666666;">Blank Database Avaliable</td>
                                <td align="left"><%=cDatabase_Blank%></td>
                                <td align="left"><%=ZZDatabase_Blank_Avaliable%></td>
                                
                            </tr>
                        </table>
                        <table cellpadding="5" cellspacing="0" width="100%" align="center" border="0">
                        <% if (_Wizard>=2) {%>
                            <tr>
                                <td colspan="5" align=left><h4>2. Database Server Settings</h4>Please enter your MSSQL database server details below...</td>
                            </tr>
                            <tr>
                                <td align="left" width="120" style="color: #666666;">Host Name:</td>
                                <td align=left width="230" align=left><input type="text" tabindex="43" name="lnk_database_host" value="<%=lnk_database_host%>"/></td>
                                <td align=left width="70" style="color: #666666;">database user:</td>
                                <td align=left><input type="text" tabindex="44" name="lnk_database_username" value="<%=lnk_database_username%>"/>
                                </td>
                            </tr>
                            <tr>
                                <td align=left width="70" style="color: #666666;">database name:</td>
                                <td align=left><input type="text" tabindex="44" name="lnk_database_name" value="<%=lnk_database_name%>"/>
                                <td align=left style="color: #666666;">database Password:</td>
                                <td align=left><input type="password" tabindex="45" name="lnk_database_password" value="<%=lnk_database_password%>"/>
                                </td>
                            </tr>
                        <% } %>
                        <% if (_Wizard>=2) {%>
				                <tr>
				                		<td colspan="8" align=left nowrap=1>&nbsp;<div style="font-weight: normal;color: red"><%=Wizard_Message%></div>
				                		</td>
        				        </tr>
				                <tr>
				                		<td  colspan="8" align="center">
				                                    <input type="submit" name="lnk_Continue" value="Continue >>"/>
				                    </td>
				                </tr>
                        <% } %>
                        </table>
                    </td>
            </table>
        </form>
    </body>
</html>
